package com.woniuxy.boot.nb_auth.controller.app;

import com.woniuxy.boot.common.dto.IdCardDTO;
import com.woniuxy.boot.common.pojo.ResponseResult;
import com.woniuxy.boot.common.util.JwtUtil;
import com.woniuxy.boot.nb_auth.bean.IdCard;
import com.woniuxy.boot.nb_auth.exception.*;
import com.woniuxy.boot.nb_auth.service.IdCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("app/idCard")
public class IdCardController {
    @Autowired
    private IdCardService idCardService;

    /**
     * @param idCard 用户绑定身份证信息
     */
    @PostMapping("bindIdCard")
    public ResponseResult<Void> bindIdCard(@RequestBody IdCard idCard, @RequestHeader("token") String token) throws IOException {
        idCard.setUserId(JwtUtil.parseJwt(token));
        idCardService.bindIdCard(idCard);
        return ResponseResult.SUCCESS;
    }
    /**
     * @param userId 根据用户的id查询回绑定身份证的信息
     */
    @GetMapping("getUserIdCard")
    public IdCardDTO getUserIdCard(@RequestParam("userId") Long userId){
        return idCardService.getUserIdCard(userId);
    }

    /**身份证全局异常处理
     * @param e
     * @return
     */
    @ExceptionHandler
    public ResponseResult<Void> exceptionHandler(Exception e) {
        if (e instanceof NameIsNullException) {
            return new ResponseResult<>(751, "开户名不能为空");
        }   if (e instanceof NameHaveSpecialCharException) {
            return new ResponseResult<>(752, "开户名不能包含特殊字符");
        } if (e instanceof IdCardIsNullException) {
            return new ResponseResult<>(753, "身份证号码不能为空");
        } if (e instanceof IdCardWrongsFormatException) {
            return new ResponseResult<>(754, "身份证号码格式错误");
        } if (e instanceof IdCardIsVoidException) {
            return new ResponseResult<>(755, "无此身份证号码");
        } if (e instanceof RealNameNoMatchingException) {
            return new ResponseResult<>(756, "身份证信息不匹配");
        } if (e instanceof SystemUpholdException) {
            return new ResponseResult<>(757, "系统维护中,请稍后再试");
        }if(e instanceof IdCardIsBindException){
            return new ResponseResult<>(758, "已经实名认证过了,无法绑定新身份证");
        }
        else if (e instanceof IOException) {
            return new ResponseResult<>(800, "IO异常");
        } else {
            return new ResponseResult<>(900, "未知异常");
        }
    }


}
